<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步函数同步化</title>
</head>
<script>
    let request = {
        getPromise(url) {
            return new Promise((resolve,reject) => {
                // 1.实例化xhr对象
                var xhr = new XMLHttpRequest();
                // 2.设置请求行
                xhr.open('get',url);
                // 3.发送请求
                xhr.send();
                // 4.设置响应结果为json
                xhr.responseType = 'json'
                // 5.监听响应
                xhr.onreadystatechange = function() {
                    if(this.readyState == 4) {
                        if(this.status == 200) {
                            resolve(this.response)
                        } else {
                            reject(this.response)
                        }   
                    }
                }                    
            })
        }
    }

    // generator实现异步代码的同步化
    function * foo() {
        let url = 'http://39.96.21.48:5588/category/findAll';
        let categories = yield call(request.getPromise,url);
        console.log('categories',categories)
    }

    let iterator = foo();
    iterator.next()
    // handler为调用方法，params为请求地址
    function call(handler,params){
      handler(params)
      .then((res)=>{
        // 将res作为当前yield表达式的返回值
        iterator.next(res)
      })
    }
</script>
<body>
    
</body>
</html>